import {AiResponse} from "./AiResponse.ts";
import {AiResponseListener} from "./AiResponseListener.ts";
import {Editor} from "@tiptap/core";
import {InnerEditor} from "../../core/AiEditor.ts";
import { uuid } from "../../util/uuid.ts";

const actionKey = "image_action";
const id = uuid();

export class DefaultAiImageListener implements AiResponseListener {
    editor: Editor;
    from: number;
    end: number;

    constructor(editor: Editor) {
        this.editor = editor;
        this.from = editor.view.state.selection.from;
        this.end = editor.view.state.selection.to;
        const {state: {tr}, view} = this.editor!
        if (!tr.selection.empty) tr.deleteSelection();

        view.dispatch(tr.setMeta(actionKey, {
            type: "add",
            id,
            pos: tr.selection.from,
        }));
    }

    onStart() {
        //do nothing
    }

    onStop() {
        //do nothing
    }

    onMessage(response: AiResponse) {
        const {state: {tr}, view} = this.editor!
        const end = this.editor.state.selection.to;
        switch(response.type) {
            case "url":
                const parseMarkdown = (this.editor as InnerEditor).parseMarkdown(`<img src=${response.data} />`);
                view.dispatch(tr.replaceWith(this.from, end, parseMarkdown).setMeta(actionKey, {type: "remove", id}).scrollIntoView());
                break
            default:
                break
        }
        this.editor.commands.scrollIntoView();
    }
}
